import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { SearchBar, Card, Button, Image } from 'antd-mobile'
import { BellOutline, HeartOutline, PlayOutline, RightOutline } from 'antd-mobile-icons'
import dataService, { type Training } from '../../services/dataService'
import TrainingInfoPopup from '../../components/training/TrainingInfoPopup'
import ActionDetailPopup from '../../components/training/ActionDetailPopup'
import AICoach from '../../components/AITalk/AICoach'

export default function Home() {
  const navigate = useNavigate()
  const [searchValue, setSearchValue] = useState('')
  const [recommendedTrainings, setRecommendedTrainings] = useState<Training[]>([])
  const [dynamicTrainings, setDynamicTrainings] = useState<Training[]>([])
  const [showTrainingPopup, setShowTrainingPopup] = useState(false)
  const [selectedTraining, setSelectedTraining] = useState<Training | null>(null)
  const [showActionPopup, setShowActionPopup] = useState(false)
  const [selectedAction, setSelectedAction] = useState<Training | null>(null)

  useEffect(() => {
    // 初始化数据
    const allTrainings = dataService.getAllTrainings()
    
    // 获取推荐课程
    const recommended = allTrainings.filter(t => t.price === '免费').slice(0, 2)
    setRecommendedTrainings(recommended)
    
    // 获取动作训练
    const dynamic = allTrainings.filter(t => t.category === '瑜伽').slice(0, 4)
    setDynamicTrainings(dynamic)
  }, [])

  // 搜索功能
  const handleSearch = (value: string) => {
    setSearchValue(value)
    if (value.trim()) {
      // 这里可以导航到搜索结果页面
      console.log('搜索:', value)
    }
  }

  // 分类数据
  const categories = [
    { id: 1, name: '力量训练', icon: '🏋️‍♀️', category: '力量训练' },
    { id: 2, name: '跳绳', icon: '🪀', category: '跳绳' },
    { id: 3, name: '动感单车', icon: '🚴‍♀️', category: '动感单车' },
    { id: 4, name: '塑形', icon: '💃', category: '塑形' }
  ]

  const navigateToCategory = (categoryName: string) => {
    navigate(`/shape?category=${encodeURIComponent(categoryName)}`)
  }

  const navigateToTraining = (training: Training) => {
    navigate(`/training-detail?id=${training.id}`)
  }

  const startBannerTraining = () => {
    // 跳转到训练详情页面，使用第一个训练项目
    const firstTraining = dynamicTrainings[0]
    if (firstTraining) {
      navigate(`/training-detail?id=${firstTraining.id}`)
    }
  }

  const closeTrainingPopup = () => {
    setShowTrainingPopup(false)
    setSelectedTraining(null)
  }

  const handleActionCardClick = (training: Training) => {
    setSelectedAction(training)
    setShowActionPopup(true)
  }

  const closeActionPopup = () => {
    setShowActionPopup(false)
    setSelectedAction(null)
  }

  return (
    <div className="home-page">
      <AICoach></AICoach>
      {/* 顶部头部 */}
      <div className="header">
        <div className="greeting">
          <span className="hello">嗨, Koto</span>
          <BellOutline 
            className="notification-icon" 
            onClick={() => navigate('/notifications')}
          />
      </div>
        
        <SearchBar
          placeholder="这里输入内容搜索"
          value={searchValue}
          onChange={setSearchValue}
          onSearch={handleSearch}
          style={{ 
            '--background': '#f5f5f5',
            '--border-radius': '20px',
            '--padding-left': '16px'
          }}
        />
      </div>

      <div className="content">
        {/* 横幅广告 */}
        <div className="banner-section">
          <div className="banner-card">
            <div className="banner-content">
              <h3>全身可强化训练</h3>
              <p>将各项一体训练的体</p>
              <p>质运动训练</p>
              <Button 
                color="warning" 
                size="small" 
                fill="solid"
                onClick={startBannerTraining}
            style={{
                  borderRadius: '20px',
                  marginTop: '12px'
                }}
          >
            开始训练
              </Button>
        </div>
            <div className="banner-image">
        <img
                src="/比心.png" 
                alt="训练"
          style={{
            width: '120px',
            height: '120px',
                  objectFit: 'contain'
          }}
        />
      </div>
          </div>
        </div>

        {/* 热门分类 */}
        <div className="section">
          <div className="section-header">
            <h3>热门分类</h3>
            <Button 
              fill="none" 
              size="mini" 
              onClick={() => navigate('/categories')}
            >
              查看全部 <RightOutline />
            </Button>
        </div>
          
          <div className="categories-grid">
            {categories.map((category) => (
              <div 
                key={category.id}
                className="category-item"
                onClick={() => navigateToCategory(category.category)}
              >
                <div className="category-icon">
                  <span>{category.icon}</span>
                </div>
                <span className="category-name">{category.name}</span>
              </div>
          ))}
        </div>
      </div>

      {/* 猜你喜欢 */}
        <div className="section">
      <div className="section-header">
            <h3>猜你喜欢</h3>
            <Button 
              fill="none" 
              size="mini" 
              onClick={() => navigate('/categories')}
            >
              查看全部 <RightOutline />
            </Button>
      </div>

          <div className="recommendations-grid">
            {recommendedTrainings.map((training) => (
              <Card
                key={training.id}
                bodyStyle={{ padding: '0' }}
                onClick={() => navigateToTraining(training)}
                style={{ 
                  borderRadius: '16px',
                  overflow: 'hidden',
                  position: 'relative'
                }}
              >
                <div className="recommendation-card">
                  <Image
                    src={training.cover}
                    alt={training.title}
                    width="100%"
                    height={120}
                    fit="cover"
                    style={{ borderRadius: '16px 16px 0 0' }}
                  />
                  <div className="heart-icon">
                    <HeartOutline />
                  </div>
                  <div className="card-info">
                    <div className="card-title">{training.title}</div>
                    <div className="card-meta">
                      <span className="duration">{training.duration}</span>
                      <span className="level">{training.level}</span>
              </div>
            </div>
        </div>
              </Card>
            ))}
          </div>
          </div>

      {/* 动作训练 */}
        <div className="section">
      <div className="section-header">
            <h3>动作训练</h3>
            <Button 
              fill="none" 
              size="mini" 
              onClick={() => navigate('/shape')}
            >
              查看全部 <RightOutline />
            </Button>
          </div>
          
          <div className="dynamic-training-list">
            {dynamicTrainings.map((training) => (
              <div 
                key={training.id}
                className="dynamic-item"
                onClick={() => handleActionCardClick(training)}
              >
                <div className="dynamic-image">
                  <Image
                    src={training.cover}
                    alt={training.title}
                    width={60}
                    height={60}
                    fit="cover"
                    style={{ borderRadius: '12px' }}
                  />
                </div>
                <div className="dynamic-info">
                  <div className="dynamic-title">{training.title}</div>
                  <div className="dynamic-duration">{training.duration}</div>
      </div>
                <Button 
                  fill="none" 
                  size="mini"
                  onClick={(e) => {
                    e.stopPropagation()
                    navigateToTraining(training)
                  }}
                >
                  <PlayOutline />
                </Button>
            </div>
        ))}
      </div>
    </div>
      </div>

      {/* 训练信息弹窗 */}
      <TrainingInfoPopup
        visible={showTrainingPopup}
        onClose={closeTrainingPopup}
        training={selectedTraining}
      />

      {/* 动作详情弹窗 */}
      <ActionDetailPopup
        visible={showActionPopup}
        onClose={closeActionPopup}
        actionName={selectedAction?.title}
        actionImage={selectedAction?.cover}
      />

      <style>{`
        .home-page {
          min-height: 100vh;
          background: #ffffff;
          padding-bottom: 80px;
        }
        
        .header {
          background: #ffffff;
          padding: 20px 16px;
          padding-top: 24px;
          box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        }
        
        .greeting {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
        }
        
        .hello {
          font-size: 26px;
          font-weight: 700;
          color: #333333;
          letter-spacing: -0.5px;
        }
        
        .notification-icon {
          font-size: 26px;
          color: #FF6B35;
          cursor: pointer;
          transition: all 0.3s ease;
          padding: 8px;
          border-radius: 50%;
        }
        
        .notification-icon:hover {
          transform: scale(1.1);
          background: rgba(255, 107, 53, 0.1);
        }
        
        .notification-icon:active {
          transform: scale(0.95);
        }
        
        .content {
          padding: 24px 16px;
          background: #ffffff;
        }
        
        .banner-section {
          margin-bottom: 32px;
        }
        
        .banner-card {
          background: linear-gradient(135deg, #FFB6C1 0%, #FFC0CB 50%, #FFCCCB 100%);
          border-radius: 24px;
          padding: 24px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          min-height: 160px;
          position: relative;
          overflow: hidden;
          box-shadow: 0 4px 20px rgba(255, 182, 193, 0.3);
        }
        
        .banner-content h3 {
          font-size: 20px;
          font-weight: 700;
          color: #333333;
          margin: 0 0 12px 0;
          letter-spacing: -0.3px;
        }
        
        .banner-content p {
          font-size: 15px;
          color: #666666;
          margin: 4px 0;
          line-height: 1.5;
        }
        
        .banner-image {
          flex-shrink: 0;
        }
        
        .section {
          margin-bottom: 32px;
        }
        
        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
        }
        
        .section-header h3 {
          font-size: 20px;
          font-weight: 700;
          color: #333333;
          margin: 0;
          letter-spacing: -0.3px;
        }
        
        .section-header .adm-button {
          color: #FF6B35;
          font-weight: 500;
        }
        
        .categories-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 16px;
          margin-bottom: 16px;
        }
        
        .category-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          cursor: pointer;
          transition: all 0.3s ease;
          padding: 8px;
          border-radius: 16px;
        }
        
        .category-item:hover {
          transform: translateY(-2px);
        }
        
        .category-item:active {
          transform: scale(0.95);
        }
        
        .category-icon {
          width: 64px;
          height: 64px;
          border-radius: 16px;
          background: #ffffff;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 10px;
          box-shadow: 0 4px 12px rgba(0,0,0,0.08);
          font-size: 26px;
          transition: all 0.3s ease;
        }
        
        .category-item:hover .category-icon {
          box-shadow: 0 6px 20px rgba(255, 107, 53, 0.2);
        }
        
        .category-name {
          font-size: 13px;
          color: #666666;
          text-align: center;
          font-weight: 500;
        }
        
        .recommendations-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 16px;
        }
        
        .recommendation-card {
          position: relative;
          background: #ffffff;
          border-radius: 20px;
          overflow: hidden;
          box-shadow: 0 4px 16px rgba(0,0,0,0.08);
          transition: all 0.3s ease;
        }
        
        .recommendation-card:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(0,0,0,0.12);
        }
        
        .heart-icon {
          position: absolute;
          top: 12px;
          right: 12px;
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background: rgba(255,255,255,0.95);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #FF6B35;
          z-index: 2;
          box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .card-info {
          padding: 16px;
        }
        
        .card-title {
          font-size: 15px;
          font-weight: 600;
          color: #333333;
          margin-bottom: 8px;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          line-height: 1.4;
        }
        
        .card-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        
        .duration {
          font-size: 13px;
          color: #999999;
          font-weight: 500;
        }
        
        .level {
          font-size: 13px;
          color: #FF6B35;
          font-weight: 600;
          background: rgba(255, 107, 53, 0.1);
          padding: 4px 8px;
          border-radius: 12px;
        }
        
        .dynamic-training-list {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }
        
        .dynamic-item {
          background: #ffffff;
          border-radius: 20px;
          padding: 16px;
          display: flex;
          align-items: center;
          gap: 16px;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 2px 12px rgba(0,0,0,0.06);
          border: 1px solid #f0f0f0;
        }
        
        .dynamic-item:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 20px rgba(0,0,0,0.1);
          border-color: rgba(255, 107, 53, 0.2);
        }
        
        .dynamic-item:active {
          transform: scale(0.98);
        }
        
        .dynamic-image {
          flex-shrink: 0;
        }
        
        .dynamic-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 6px;
        }
        
        .dynamic-title {
          font-size: 15px;
          font-weight: 600;
          color: #333333;
          line-height: 1.4;
        }
        
        .dynamic-duration {
          font-size: 13px;
          color: #999999;
          font-weight: 500;
        }
        
        /* Orange button styling for interactive elements */
        .adm-button[color="warning"] {
          --background-color: #FF6B35;
          --text-color: #ffffff;
          --border-color: #FF6B35;
          font-weight: 600;
          box-shadow: 0 4px 12px rgba(255, 107, 53, 0.3);
          transition: all 0.3s ease;
        }
        
        .adm-button[color="warning"]:hover {
          --background-color: #E55A2B;
          --border-color: #E55A2B;
          transform: translateY(-1px);
          box-shadow: 0 6px 16px rgba(255, 107, 53, 0.4);
        }
        
        .adm-button[color="warning"]:active {
          transform: translateY(0);
        }
      `}</style>
    </div>
  )
}